import { getPrice } from "@/api/index";
import { cache, showToast } from "@/util/index";
import { upOrder } from "@/api/index";
import { subscriptionManager } from "@/util/index";
interface BackendPriceItem {
  _id: string;
  categoryId: {
    _id: string;
    name: string;
    parentId: string;
    defaultUnit: string;
    remark: string;
  }[];
  unitPrice: number; // 单位：分
  remark: string;
}

// (修改点 1) 定义后端返回数据的类型为 BackendPriceItem 数组
type BackendPriceData = BackendPriceItem[];

// 定义页面UI所需的数据结构 (这部分保持不变)
interface Tag {
  name: string;
  selected: boolean;
  _id: string; // 原始物品ID
  remark?: string; // 备注
}

interface Category {
  name: string;
  icon: string;
  selected: boolean;
  tags: Tag[];
  parentId: string;
}

Page({
  data: {
    activeNames: ["0"],
    address: "",
    categories: [] as Category[],
    activeCategoryIndex: 0,
    weights: [
      { text: "10-20kg", income: "5-20元" },
      { text: "20-50kg", income: "20-50元" },
      { text: "50-100kg", income: "50-120元" },
      { text: "100kg以上", income: "120元以上" },
    ],
    weightIndex: 0,
    fileList: [],
    isPriceLoading: true,
    remarkContent: "",
  },
  onShow() {
    const address = cache.get("address");
    if (address) {
      this.setData({ address });
    }
  },
  upload(e) {
    this.data.fileList = e.detail.value;
  },
  async onLoad() {
    this.setData({ isPriceLoading: true });
    wx.getFuzzyLocation({
      success: async (res) => {
        try {
          const data: BackendPriceData = await getPrice({
            latitude: res.latitude,
            longitude: res.longitude,
          });
          const formattedCategories = this.processPriceData(data);
          this.setData({
            categories: formattedCategories,
          });
        } catch (error) {
          console.error("获取价格数据失败", error);
          wx.showToast({ title: "加载价格失败", icon: "none" });
        } finally {
          this.setData({ isPriceLoading: false });
        }
      },
      fail: (err) => {
        this.setData({ isPriceLoading: false });
        console.error("获取地理位置失败", err);
        wx.showToast({ title: "请授权地理位置", icon: "none" });
      },
    });
  },

  /**
   * @description 处理后端返回的价格数据，将其转换为页面所需的层级结构
   * @param rawData - 后端返回的原始数据数组
   * @returns {Category[]} - 格式化后的分类数组
   */
  processPriceData(rawData: BackendPriceData): Category[] {
    // 父分类的映射关系保持不变
    const parentCategoryMap: {
      [key: string]: { name: string; icon: string };
    } = {
      "684c4d60189f86d5e167370b": {
        name: "纸品类",
        icon: "/static/images/index/paper.png",
      },
      "68334bee466d41ac68b63457": {
        name: "旧衣类",
        icon: "/static/images/index/cloths.png",
      },
      "68334c35ce5ec90ca62617ff": {
        name: "金属类",
        icon: "/static/images/index/steels.png",
      },
      "68334c55e0ec19cd9271d2f3": {
        name: "塑料类",
        icon: "/static/images/index/plastic.png",
      },
      "68334c1c1498549d7b713dfb": {
        name: "数码类",
        icon: "/static/images/index/electronics.png",
      },
    };

    const groupedByCategory: { [key: string]: Category } = {};

    // (修改点 3) 遍历原始数据数组，将 for...in 循环改为 for...of 循环
    for (const item of rawData) {
      // item 现在直接就是 BackendPriceItem 对象，不再需要 rawData[key]
      if (!item.categoryId || item.categoryId.length === 0) continue;

      const categoryInfo = item.categoryId[0];
      const parentId = categoryInfo.parentId;

      if (!parentCategoryMap[parentId]) continue;

      if (!groupedByCategory[parentId]) {
        groupedByCategory[parentId] = {
          ...parentCategoryMap[parentId],
          parentId: parentId,
          selected: false,
          tags: [],
        };
      }

      const newTag: Tag = {
        _id: item._id,
        name: `${categoryInfo.name} ${item.unitPrice / 100}元/${
          categoryInfo.defaultUnit
        }`,
        selected: false,
        remark: item.remark,
      };
      groupedByCategory[parentId].tags.push(newTag);
    }

    return Object.values(groupedByCategory);
  },

  /**
   * @description 选中子分类标签的事件处理
   * (此函数及以下其他函数均无需修改)
   */
  onTagSelect(e: WechatMiniprogram.TouchEvent) {
    const { categoryIndex, tagIndex } = e.currentTarget.dataset;
    const categories = this.data.categories;
    const tagSelectedPath = `categories[${categoryIndex}].tags[${tagIndex}].selected`;
    const currentTagSelectedState =
      categories[categoryIndex].tags[tagIndex].selected;

    categories[categoryIndex].tags[
      tagIndex
    ].selected = !currentTagSelectedState;

    const isParentSelected = categories[categoryIndex].tags.some(
      (tag) => tag.selected
    );
    const parentSelectedPath = `categories[${categoryIndex}].selected`;

    this.setData({
      [tagSelectedPath]: !currentTagSelectedState,
      [parentSelectedPath]: isParentSelected,
    });
  },

  // --- 以下是页面中其他既有方法，保持不变 ---

  onCollapseChange(event: any) {
    this.setData({
      activeNames: event.detail,
    });
  },

  onSelectAddress() {
    wx.navigateTo({
      url: "../address_list/index",
    });
  },

  onCategorySelect(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index as number;
    if (this.data.activeCategoryIndex !== index) {
      this.setData({
        activeCategoryIndex: index,
      });
    }
  },

  onWeightSelect(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index as number;
    if (this.data.weightIndex !== index) {
      this.setData({
        weightIndex: index,
      });
    }
  },

  async onSubmitOrder() {
    const selectedItems: { category: string; item: string; _id: string }[] = [];
    this.data.categories.forEach((category) => {
      category.tags.forEach((tag) => {
        if (tag.selected) {
          selectedItems.push({
            category: category.name,
            item: tag.name,
            _id: tag._id,
          });
        }
      });
    });

    if (selectedItems.length === 0) {
      wx.showToast({ title: "请选择回收物品", icon: "none" });
      return;
    }
    if (!this.data.address) {
      wx.showToast({ title: "请选择回收地址", icon: "none" });
      return;
    }
    await subscriptionManager([
      "recyclePlaceAnOrderNotice",
      "recycleSuccessNotice",
      "recycleFailNotice"
    ]);
    const { _id, campus, address, formatted_address } = this.data.address;
    const data = await upOrder({
      school: address,
      formatted: formatted_address,
      campus: campus,
      address: _id,
      category: selectedItems.map((i) => i.item.split(" ")[0]),
      weight: this.data.weights[this.data.weightIndex].text,
      remark: this.data.remarkContent,
      urls: this.data.fileList,
    });
    if (data.id) {
      showToast("下单成功");
      wx.navigateBack();
    }
  },
});
